﻿using AnlianCommon.Common.Domains.UserPermissions;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AnlianCommon.API.Commands.RolePerms
{
    public class RolePermDeletedHandler : IRequestHandler<RolePermDeletedCommand, Result>
    {
        private readonly IBaseRepository<RolePerm> _rolePermRepository;

        public RolePermDeletedHandler(IBaseRepository<RolePerm> rolePermRepository)
        {
            _rolePermRepository = rolePermRepository;
        }
        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(RolePermDeletedCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Deleted };
            try
            {
                var rolePerm = await (await _rolePermRepository.GetAll()).Where(c=>c.RolePermId==request.RolePermId).FirstOrDefaultAsync();
                if (rolePerm != null)
                {
                    rolePerm.IsDeleted = true;
                    rolePerm.DeletedOwnerId = "张三";
                    rolePerm.DeletedTime = DateTime.Now;
                    var res = await _rolePermRepository.Update(rolePerm);
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Msg = "删除成功";
                    }
                    else
                    {
                        result.Code = (int)CommonErrorCode.Deleted;
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
